<?php

class AuthController extends Zend_Controller_Action
{

    public function init()
    {
        $this->view->site = $this->getRequest()->getControllerName();
    }

    public function preDispatch() {
        parent::preDispatch();
        $this->_helper->layout()->disableLayout();
    }
    
    public function indexAction()
    {
        if(Zend_Auth::getInstance()->hasIdentity())
            $this->_redirect ('/');
        else
            $this->_redirect ('/auth/login');
    }

    public function loginAction()
    {   
        if(Zend_Auth::getInstance()->hasIdentity())
            $this->_redirect ('/');
        
        $request = $this->getRequest();
        $form = new Application_Form_LoginForm();
        
        if($request->isPost())
        {
            if($form->isValid($this->_request->getPost()))
            {
                $authAdapter = $this->getAuthAdapter();

                $username = $form->getValue('username');
                $password = $form->getValue('password');

                $authAdapter->setIdentity($username)
                            ->setCredential($password);

                $auth = Zend_Auth::getInstance();

                $result = $auth->authenticate($authAdapter);

                if($result->isValid())
                {
                    $identity = $authAdapter->getResultRowObject();

                    $authStorage = $auth->getStorage();
                    $authStorage->write($identity);
            
                    $this->_redirect('/');
                }
                else
                {
                    $this->view->errorMessage = 'Username or Password is Wrong !';
                }
            }
        }
        
        $this->view->form = $form;
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/');
    }

    private function getAuthAdapter()
    {
        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
        $authAdapter->setTableName('tabel_user')
                    ->setIdentityColumn('username')
                    ->setCredentialColumn('password');
        
        return $authAdapter;
        
    }
}





